package com.ipet.web.spring.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.*;


/**
 * Redis Cluster 配置类
 * Created by lujun.chen on 2017/3/3.
 */
@Configuration
@ConditionalOnClass(RedisClusterConfig.class)
@EnableConfigurationProperties(RedisClusterProperties.class)
@PropertySource(value="classpath:redis.properties")
public class RedisClusterConfig {

    @Resource
    private RedisClusterProperties redisClusterProperties;
    
    @Value("${redis.maxIdle}")
	private Integer maxIdle;
	
	@Value("{redis.maxWaitMillis}")
	private String maxWaitMillis;
	
	@Value("${redis.testOnBorrow}")
	private Boolean testOnBorrow;
	
	@Value("${redis.maxTotal}")
	private Integer maxTotal;
	
	@Value("${redis.minIdle}")
	private Integer minIdle;
	
	@Value("${redis.timeout}")
	private int timeout;
	
	private  JedisPoolConfig jedisPoolConfig(){
		System.out.println(maxWaitMillis.getClass());
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMaxWaitMillis(1000);
		jedisPoolConfig.setTestOnBorrow(testOnBorrow);
		jedisPoolConfig.setMaxTotal(maxTotal);
		jedisPoolConfig.setMinIdle(minIdle);
		
		return jedisPoolConfig;
		
		
	}
    @Bean
    public JedisCluster redisCluster(){

        Set<HostAndPort> nodes = new HashSet<>();
        for (String node:redisClusterProperties.getNodes()){
            String[] parts= StringUtils.split(node,":");
            Assert.state(parts.length==2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'");
            nodes.add(new HostAndPort(parts[0], Integer.valueOf(parts[1])));
        }
        return new JedisCluster(nodes, timeout, jedisPoolConfig()) ;
    }


}
